package com.lonwin.inspectionmanagement.mvp.presenter;

import android.app.Application;
import android.util.ArrayMap;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.geocoder.StreetNumber;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.functions.Consumer;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;

import javax.inject.Inject;

import com.jess.arms.utils.DataHelper;
import com.lonwin.inspectionmanagement.app.AppConstants;
import com.lonwin.inspectionmanagement.app.utils.AppUtil;
import com.lonwin.inspectionmanagement.app.utils.DataUtil;
import com.lonwin.inspectionmanagement.app.utils.GPSUtil;
import com.lonwin.inspectionmanagement.app.utils.RxUtils;
import com.lonwin.inspectionmanagement.mvp.contract.HomeCruiseContract;
import com.lonwin.inspectionmanagement.mvp.model.api.Api;
import com.lonwin.inspectionmanagement.mvp.model.api.AppConstant;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ConfigBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.NLocusSResult;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.PatrolBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.QueryNumBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.SearLocusBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


@ActivityScope
public class HomeCruisePresenter extends BasePresenter<HomeCruiseContract.Model, HomeCruiseContract.View> implements GeocodeSearch.OnGeocodeSearchListener {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private GeocodeSearch geocodeSearch;

    private  ConfigBean configBean ;
    @Inject
    public HomeCruisePresenter(HomeCruiseContract.Model model, HomeCruiseContract.View rootView) {
        super(model, rootView);
        geocodeSearch = new GeocodeSearch(mRootView.getActivity());
        geocodeSearch.setOnGeocodeSearchListener(this);
        configBean = DataHelper.getDeviceData(mRootView.getActivity(), AppConstants.EXTRA_CONFIG_DATA);

    }

    public ConfigBean getConfigBean() {
        return configBean;
    }

    /**
     * 暂停后继续记录轨迹
     * @param gjid
     */
    public void  continueXcpathTemp(String gjid )
    {
        Map<String,Object> maps =new HashMap<>();
        maps.put("gjid",gjid);
        mModel.continueXcpathTemp(DataUtil.getJNUrl(configBean)+"/hzxh/xcpathTempController/continueXcpathTemp",maps).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new Consumer<NLocusSResult>() {
                    @Override
                    public void accept(NLocusSResult nLocusSResult) throws Exception {
                      mRootView.continueXcpathTemp(nLocusSResult.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                      mRootView.showMessage("继续记录轨迹获取数据异常");
                    }
                });
    }
    /**
     * 获取最后一个轨迹
     */
    public void getMyLastXcpath() {
        Map<String,Object> maps =new HashMap<>();
        maps.put("gpsid",configBean.getGpsId());
        maps.put("projectid",configBean.getProjectId());
       mModel.getMyLastXcpath(DataUtil.getJNUrl(configBean)+"/hzxh/xcpathTempController/getMyLastXcpath",maps).compose(RxUtils.applySchedulers(mRootView))
               .subscribe(new Consumer<NLocusSResult>() {
                   @Override
                   public void accept(NLocusSResult nLocusSResult) throws Exception {
                       DataHelper.saveDeviceData(mAppManager.getCurrentActivity(), AppConstant.NLOCUSRESULT_DATABEAN_KEY,nLocusSResult.getData());
                       mRootView.getMyLastXcpathSuccess(nLocusSResult.getData());
                   }
               }, new Consumer<Throwable>() {
                   @Override
                   public void accept(Throwable throwable) throws Exception {
                       DataHelper.saveDeviceData(mAppManager.getCurrentActivity(), AppConstant.NLOCUSRESULT_DATABEAN_KEY,null);
                       mRootView.getMyLastXcpathSuccess(null);

                   }
               });
    }


        /**
         * 开始暂停结束
         * /**
         *  * 轨迹状态 0--打点中 1--暂停 2--结束
         *
         * @param type
         * @param maps
         */
     public void cpathTemp(String  type,Map<String,Object> maps)
     {
        String url=DataUtil.getJNUrl(configBean)+"/hzxh";
//     String url="http://hzz.lonhcloud.cn/hzxh";
        if ("start".equals(type))
        {
            url+="/xcpathTempController/startXcpathTemp";
        }else if ("pause".equals(type)){
            url+="/xcpathTempController/pauseXcpathTemp";
        }else {
            url+="/xcpathTempController/stopXcpathTemp";
        }
        mModel.cpathTemp(url,maps).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<NLocusSResult>(mErrorHandler) {
                    @Override
                    public void onNext(NLocusSResult nLocusSResult) {
                       if (nLocusSResult!=null&&nLocusSResult.getCode()==0)
                       {
                           mRootView.cpathTempSuccess(nLocusSResult.getData());
                           if ("start".equals(type))
                           {
                               mRootView.showMessage("开始记录轨迹");

                           }else if ("pause".equals(type)){
                               mRootView.showMessage("暂停记录轨迹");

                           }else {
                               mRootView.showMessage("结束记录轨迹");
                           }
                           //保存最后一个记录
                           DataHelper.saveDeviceData(mAppManager.getCurrentActivity(), AppConstant.NLOCUSRESULT_DATABEAN_KEY,nLocusSResult.getData());
                       }else {
                           if ("start".equals(type))
                           {
                               mRootView.showMessage("开始记录轨迹失败");

                           }else if ("pause".equals(type)){
                               mRootView.showMessage("暂停记录轨迹失败");

                           }else {
                               mRootView.showMessage("结束记录轨迹失败");
                           }
                       }

                    }
                });
     }

    /**
     * 反地理编码
     *
     * @param lat
     * @param lont
     */
    public void locatonForAddress(double lat, double lont) {
        //wgs84 转高德坐标系
        double[] latlont=GPSUtil.gps84_To_Gcj02(lat,lont);
        LatLonPoint latLonPoint = new LatLonPoint(latlont[0], latlont[1]);
//        LatLonPoint latLonPoint = new LatLonPoint(lat, lont);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 100f, GeocodeSearch.AMAP);
        //异步查询
        geocodeSearch.getFromLocationAsyn(query);
    }

    /**
     * 开始巡河
     *
     * @param
     * @param
     */
    public void startPatrol(String groupId, String groupname, String startaddr) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject();
            jsonObject.put("gpsid", String.valueOf(configBean.getGpsId()));
            jsonObject.put("gpsnm", configBean.getGpsName());
            jsonObject.put("startaddr", startaddr);
            jsonObject.put("groupid", groupId);
            jsonObject.put("acdc", configBean.getAdcd());
            jsonObject.put("acdcname", configBean.getAdcdName());
            jsonObject.put("groupname", groupname);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> maps = new HashMap<>();
        maps.put("data", jsonObject.toString());
        mModel.startPatrol(DataUtil.getJNUrl(configBean) + "/webmvc/v1/taskhzz/startPath", maps)
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<PatrolBean>(mErrorHandler) {
                    @Override
                    public void onNext(PatrolBean patrolBean) {
                        if (patrolBean == null) {
                            return;
                        }
                        mRootView.startPatrolSuccess(patrolBean);
                    }
                });
    }

    /**
     * 结束巡河
     *
     * @param id
     * @param km
     * @param
     */
    public void endPatrol(String id, String km, String endaddr) {

        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject();
            jsonObject.put("id", id);
            jsonObject.put("km", km);
            jsonObject.put("endaddr", endaddr);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Map<String, String> maps = new HashMap<>();
        maps.put("data", jsonObject.toString());
        mModel.endPatrol(DataUtil.getJNUrl(configBean) + "/webmvc/v1/taskhzz/endPath", maps)
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<PatrolBean>(mErrorHandler) {
                    @Override
                    public void onNext(PatrolBean patrolBean) {
                        mRootView.endPatrolSuccess(patrolBean);
                    }
                });
    }

    /**
     * 上传轨迹到定位中心
     *
     * @param data
     */
    public void updateData(String data) {
        Map<String, String> mapData = new HashMap<>();
        mapData.put("data", data);
//        DataUtil.getSJUrl(configBean)
        mModel.updateData(DataUtil.getSJUrl(configBean)+ "api/v1/data/"+configBean.getProjectId(), mapData).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onNext(String s) {
                        mRootView.updateDataSuccess(s);
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();

        StringBuilder temAdderss = new StringBuilder();
        String province = regeocodeAddress.getProvince();//省
        String city = regeocodeAddress.getCity();//州市
        String count = regeocodeAddress.getDistrict();//县区
        String shipaddress = regeocodeAddress.getTownship();//村、街道
        String formataddress = regeocodeAddress.getFormatAddress();//完整的地址
        StreetNumber streetNumber = regeocodeAddress.getStreetNumber();//具体哪条路和门牌号
        String streetNumberStr = streetNumber.getStreet() + streetNumber.getNumber();//具体哪条路和门牌号字符串
        int index = formataddress.indexOf(shipaddress);
        String mapaddress = formataddress.substring(index + shipaddress.length(), formataddress.length());

        String temHtml = "";
        String firstAddress = "";
        String subAddress = "";
        if (formataddress.length() > temAdderss.append(province).append(city).append(count).append(shipaddress).toString().length()) {
            temHtml = "<font color='#494949'size='14'>" + formataddress.substring(temAdderss.length(), formataddress.length()) + "</font><br> <font color='#888888'size='10'>" + count + shipaddress + "</font>";
            firstAddress = formataddress.substring(temAdderss.length(), formataddress.length());
            subAddress = count + shipaddress;
        } else {
            if (shipaddress != null && shipaddress.length() > 0) {
                temHtml = "<font color='#494949'size='14'>" + shipaddress + "</font><br> <font color='#888888'size='10'>" + city + count + "</font>";
                firstAddress = shipaddress;
                subAddress = city + count;
            } else {
                temHtml = "<font color='#494949'size='14'>" + city + count + "</font><br> <font color='#888888'size='10'>" + province + "</font>";
                firstAddress = city + count;
                subAddress = province;
            }
        }
//        mRootView.regeocodeAddress(firstAddress + subAddress);
        mRootView.regeocodeAddress(firstAddress);
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
    /**
     * 获取提示数据
     */
    public void getHzUnCheckXcjlbCount(){
        if (configBean!=null)
        {
            if (configBean.getCurrentRole().getRoleCode().equals(AppConstants.ROLE_LLY)||configBean.getCurrentRole().getRoleCode().equals(AppConstants.ROLE_LDBM))
            {
                //联络员
                Map<String,Object> maps=new ArrayMap<>();
                maps.put("groupids",AppUtil.getgroupids(configBean));
                mModel.getHzUnCheckXcjlbCount(DataUtil.getJNUrl(configBean)+"/hzxh/xcrecordController/getBacklogXcjlbCount",maps).compose(RxUtils.applySchedulers(mRootView))
                        .subscribe(new ErrorHandleSubscriber<QueryNumBean>(mErrorHandler) {
                            @Override
                            public void onNext(QueryNumBean queryNumBean) {
                                if (queryNumBean!=null&&(queryNumBean.getData().getDoing()+queryNumBean.getData().getDone())>0)
                                {
                                    if (queryNumBean.getData().getDoing()>0)
                                    {
                                        mRootView.getCheckCount("您有 "+queryNumBean.getData().getDoing()+" 份巡查记录表待处理",queryNumBean.getData().getDoing());
                                    }else {
                                        mRootView.getCheckCount("查看历史巡查记录表",queryNumBean.getData().getDone());
                                    }
                                }else {
                                    mRootView.getCheckCount("",0);
                                }
                            }
                        });
            }else if (configBean.getCurrentRole().getRoleCode().equals(AppConstants.ROLE_HZ))
            {
                //河长
                Map<String,Object> maps=new ArrayMap<>();
                maps.put("hzid",configBean.getGpsId());
                mModel.getHzUnCheckXcjlbCount(DataUtil.getJNUrl(configBean)+"/hzxh/xcrecordController/getHzUnCheckXcjlbCount",maps).compose(RxUtils.applySchedulers(mRootView))
                        .subscribe(new ErrorHandleSubscriber<QueryNumBean>(mErrorHandler) {
                            @Override
                            public void onNext(QueryNumBean queryNumBean) {
                                if (queryNumBean!=null&&(queryNumBean.getData().getDoing()+queryNumBean.getData().getDone())>0)
                                {
                                    if (queryNumBean.getData().getDoing()>0)
                                    {
                                        mRootView.getCheckCount("您有 "+queryNumBean.getData().getDoing()+" 份巡查记录表待签批",queryNumBean.getData().getDoing());
                                    }else {
                                        mRootView.getCheckCount("查看历史巡查记录表",queryNumBean.getData().getDone());
                                    }
                                }else {
                                    mRootView.getCheckCount("",0);
                                }

                            }
                        });
            }
        }
    }
}
